# main_ocr.py
import base64
import datetime
import io
import time
import uuid
from operator import truediv

from PIL import Image
from anyio import sleep
from fastapi import FastAPI, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse

from ocr_util import text_ocr

app = FastAPI()
# win
uploadPath = "D:/clark/personage/python/OCR/server/img/"

# docker
# uploadPath = "/paddle/uploadFile/"


from fastapi import FastAPI
from pydantic import BaseModel


class OcrModel(BaseModel):
    base64Img: str
    language: str


app.add_middleware(
    CORSMiddleware,
    # 允许跨域的源列表，例如 ["http://www.example.org"] 等等，["*"] 表示允许任何源
    allow_origins=["*"],
    # 跨域请求是否支持 cookie，默认是 False，如果为 True，allow_origins 必须为具体的源，不可以是 ["*"]
    allow_credentials=False,
    # 允许跨域请求的 HTTP 方法列表，默认是 ["GET"]
    allow_methods=["*"],
    # 允许跨域请求的 HTTP 请求头列表，默认是 []，可以使用 ["*"] 表示允许所有的请求头
    # 当然 Accept、Accept-Language、Content-Language 以及 Content-Type 总之被允许的
    allow_headers=["*"],
    # 可以被浏览器访问的响应头, 默认是 []，一般很少指定
    # expose_headers=["*"]
    # 设定浏览器缓存 CORS 响应的最长时间，单位是秒。默认为 600，一般也很少指定
    # max_age=1000
)


@app.get(path="/",summary="首页")
async def A():
    res = "OCR Server V1.0"
    return JSONResponse(content={"message": res}, status_code=200)

@app.get("/test")
async def test():
    res = "OCR testtesttest"
    return JSONResponse(content={"message": res}, status_code=200)


# 上传图片文件 来识别文字
@app.post(path="/fileImgOcr",summary="上传图片文件识别文字")
async def fileImgOcr(file: UploadFile,  language: str):
    print(file.filename)
    try:
        # 检查文件是否上传成功
        if file.content_type.startswith('image'):
            # 指定本地文件保存路径
            suffix = file.filename.split(".")[1]
            fileName = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) + "_" + str(
                uuid.uuid1()) + "." + suffix

            filePath = uploadPath + fileName
            with open(filePath, "wb") as f:
                f.write(file.file.read())
            res = text_ocr(filePath, language)
            return JSONResponse(content={"message": res}, status_code=200)
        else:
            return JSONResponse(content={"message": "Invalid file format. Only images are allowed."}, status_code=400)
    except Exception as e:
        return JSONResponse(content={"message": str(e)}, status_code=500)


# 根据图片base64格式 识别文字

@app.post(path="/base64ImgOcr",summary="根据图片base64格式 识别文字")
async def base64ImgOcr(ocrModel: OcrModel):
    print(ocrModel)
    status = 0
    res = ""
    try:
        header, content = ocrModel.base64Img.split(",")
        suffix = header[11:14]
        fileName = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) + "_" + str(uuid.uuid1()) + "." + suffix
        filePath = uploadPath + fileName

        imgdata = base64.b64decode(content)
        image = Image.open(io.BytesIO(imgdata))
        image.save(filePath)
        res = text_ocr(filePath, ocrModel.language)
        status = 200
    except Exception as e:
        status = 500
    finally:
        # 关闭图像对象和二进制流
        # 关闭图像对象和二进制流
        image.close()
    return JSONResponse(content={"message": res}, status_code=status)

#
# #  根据图片绝对路径获取识别文字
# #  注意：使用该接口时候启动 需要docker 映射宿主机的本地目录才行。
# @app.get("/filePathImgOcr")
# async def filePathImgOcr(filePath: str, language: str):
#     try:
#         res = text_ocr(filePath, language)
#         return JSONResponse(content={"message": res}, status_code=200)
#     except Exception as e:
#         return JSONResponse(content={"message": str(e)}, status_code=500)
#
#
# #  根据图片名称来识别，前提是图片文件已在容器中，或者已映射宿主机
# @app.get("/imgNameOcr")
# async def imgNameOcr(imgName: str, language: str):
#     try:
#         res = text_ocr(uploadPath + imgName, language)
#         return JSONResponse(content={"message": res}, status_code=200)
#     except Exception as e:
#         return JSONResponse(content={"message": str(e)}, status_code=500)


# 在最下面加上 这一句 代替命令行启动
if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app='main_ocr:app', host="0.0.0.0", port=8888, reload=True)
